﻿using Api_Core_Spider.Models;
using Api_Core_Spider.Services;
// Services/ActivationMiddleware.cs
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Text.Json;

namespace Api_Core_Spider.Services
{
    /// <summary>
    /// 激活中间件
    /// </summary>
    public class ActivationMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ActivationService _activationService;

        public ActivationMiddleware(RequestDelegate next, ActivationService activationService)
        {
            _next = next;
            _activationService = activationService;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            // 放行激活相关接口（避免循环拦截）
            if (context.Request.Path.StartsWithSegments("/api/activation", StringComparison.OrdinalIgnoreCase))
            {
                await _next(context);
                return;
            }

            // 获取激活服务
            var activationService = context.RequestServices.GetRequiredService<IActivationService>();

            // 获取当前请求的 MachineInfo（可从请求头、Body 或自定义逻辑获取）
            var machineInfo = context.Request.Headers["MachineInfo"]
                .FirstOrDefault() //先获取第一个字符串值
                ?.FromJson<MachineInfo>(); // 需实现 FromJson 扩展方法

            // 校验激活状态
            if (machineInfo == null || !activationService.IsActivated(machineInfo))
            {
                context.Response.StatusCode = 403; // 未激活返回 403
                await context.Response.WriteAsync("系统未激活，请先激活");
                return;
            }

            // 激活状态有效，继续执行
            await _next(context);
        }
    }

    // 扩展方法：简化 JSON 反序列化
    public static class HttpContextExtensions
    {
        public static T FromJson<T>(this string json)
        {
            return  System.Text.Json.JsonSerializer.Deserialize<T>(json);
        }
    }
}